' Sort Strings
' This program prompts the user for a list of names and then sorts the
'   names alphabetically.

' Set maximum number of lines that can be entered and declare string
'   array to hold lines.

maxLines% = 15   ' maxLines% will be shared with the GetText subprogram
DIM inputLines$(maxLines%)

CLS

' Call GetText subprogram to get input from user; at return, the
'   numOfElements% variable will contain number of lines received.

CALL GetText (inputLines$(), numOfElements%)

' Call ShellSort subprogram to put inputLines$ array in
'   alphabetic order.

CALL ShellSort (inputLines$(), numOfElements%)

PRINT
PRINT "Sorting results:"
PRINT

FOR i% = 1 TO numOfElements%    ' print contents of sorted array
    PRINT inputLines$(i%)
NEXT i%

PRINT
INPUT "Press Return to continueI", dummy$

END

SUB GetText (strArray$(), count%) STATIC

' The GetText subprogram fills the strArray$ array with text
'   entered at the keyboard.  The number of lines that can be
'   entered is determined by the shared variable maxLines%.
'   Both strArray$ and count% (the number of lines actually
'   entered) are returned to the main program.

SHARED maxLines%     ' Get maxLines% from the main program

PRINT "Enter up to"; maxLines%; "lines of text; to end, ";
PRINT "press Return on a new line."
PRINT

count% = 0                    ' initialize variables to zero and "empty"
inLine$ = "empty"

' Loop until count% = maxLines% or an empty line is received.

WHILE (count% < maxLines%) AND (inLine$ <> "")
    LINE INPUT "-> "; inLine$  ' get line from user
    IF (inLine$ <> "") THEN    ' if line is not blank, copy it
        count% = count% + 1    '   to the strArray$ array
        strArray$(count%) = inLine$
    END IF
WEND

END SUB

SUB ShellSort (strArray$(), numOfElements%) STATIC

' The ShellSort subprogram sorts the elements of strArray$ and
'   returns strArray$ to the main program.  The numOfElements%
'   argument contains the number of elements in strArray$.
'   ShellSort sorts elements in decending order.

span% = numOfElements% \ 2
   
WHILE span% > 0
    FOR i% = span% TO numOfElements% - 1
        j% = i% - span% + 1
        FOR j% = (i% - span% + 1) TO 1 STEP -span%
            IF strArray$(j%) <= strArray$(j% + span%) THEN
                j% = 1
            ELSE   ' swap array elements that are out of order
                SWAP strArray$(j%), strArray$(j% + span%)
            END IF
        NEXT j%
    NEXT i%
    span% = span% \ 2
WEND

END SUB
